package com.example.checkqufuface.View;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.checkqufuface.Base.BaseActivity;
import com.example.baselibrary.Bean.CheckResultBean;
import com.example.baselibrary.Interface.FacePickInterface;
import com.example.baselibrary.Utils.Customer;
import com.example.baselibrary.Utils.FaceCj;
import com.example.baselibrary.Utils.FaceMasks;
import com.example.baselibrary.Utils.LogUtil;
import com.example.baselibrary.Utils.MyBitmapUtils;
import com.example.baselibrary.Utils.OutFace;
import com.example.checkqufuface.Utils.SelfToastUtil;
import com.example.baselibrary.Utils.ToastUtil;
import com.example.checkqufuface.BarcodeScanner.BarcodeScannerResolver;
import com.example.checkqufuface.Customer.MyImageView;

import com.example.checkqufuface.ProcessorThink.FaceCheck;
import com.example.checkqufuface.ProcessorThink.QRcodeCheck;
import com.example.checkqufuface.R;
import com.example.checkqufuface.Utils.SHExtends;
import com.example.facechecklibrary.constant.Global;
import com.faceplusplus.api.FaceDetecter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Locale;

public class AnhuiActivity extends BaseActivity implements SurfaceHolder.Callback, Camera.PreviewCallback, View.OnClickListener {

    private static final String TAG = "AnhuiActivity";
    RelativeLayout rlMessage;
    SurfaceView svPreview;
    ImageView m_titleFace;
    TextView m_titleResult;
    MyImageView m_messageResult;
    LinearLayout mllTitlebg;
    RelativeLayout m_rlMessageFace;
    ImageView m_ivFace;
    ImageView iv_Test;
    EditText etScan;
    static Button btConfig;
    static Button btAgain;
    static Button btReset;
    private FaceMasks fmMask;
    private HandlerThread handleThread;
    private Handler detectHandler;
    private Camera mCamera;
    private int width = 1280;
    private int height = 720;
    //初始化
    private FaceDetecter facedetecter;
    Activity activity;
    private int faceNumber;
    private static int faceType;

    private Bitmap bitmap;
    private Bitmap bitmap1;
    private Bitmap bitmap_collect;
    private static String basa64;
    //当是在人脸录完检票 就停止 持续的人脸检票
    private static boolean FaceFirst;

    //与 handler 配合  处理 验证信息
    private static final int PROCESSOR_QRCODE = 10;
    private static final int PROCESSOR_IDCODE = 20;
    private static final int PROCESSOR_ICCODE = 30;
    private static final int PROCESSOR_GATE = 40;
    private static final int PROCESSOR_FACE = 50;
    private static final int PICK_FACE = 60;
    private static final int CHECK_FACE = 70;
    private static final int INITIALIZATION_THREAD = 80;  //初始化线程，让线程开启然后去刷卡
    private static final int CONTINUE_BRUSH = 90;  //等线程初始化后 再去操作
    private MyHandler mMyHandler = new MyHandler(AnhuiActivity.this);

    private static Runnable runnableID;
    private static Runnable iniThreadRunable;
    //二维码扫描
    private BarcodeScannerResolver mBarcodeScannerResolver;
    private long barcode_exitTime;
    private static long reqTwo = 5000;
    private static long betweenTime = 3000;
    private static String numberAll;
    private static String qrCheck = "";
    private static long reqOne = 0;
    private int testType;

    //  由于是 usb 扫描  所以 就 不用 串口代码了
    private String barcode = "";
    private boolean IDopen = false;
    //是否需要采集人脸
    private static boolean PickFace = false;
    private static Runnable feceNeed;

    private static CheckResultBean checkResultBean = new CheckResultBean();
    private static SHExtends she;
    private static boolean isPickFace = false;

    private static TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调
    private String string;
    private boolean isSendFace = false;
    private int pickFaceNum = 0;

    //初始化语音
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {

                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    //使用handler 进行 线程通信
    private static class MyHandler extends Handler {
        private WeakReference<AnhuiActivity> activityWeakReference;

        public MyHandler(AnhuiActivity anhuiActivity) {
            activityWeakReference = new WeakReference<AnhuiActivity>(anhuiActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final AnhuiActivity anhuiActivity = activityWeakReference.get();
            if (anhuiActivity != null) {
                if (faceType == 0) {
                    isPickFace = false;
                }
                switch (msg.what) {
                    case PROCESSOR_QRCODE:
                        //如果正在采集人脸，那么就 不让去 其他操作
                        //接收到二维码 应该去  网络请求判断
                        if (!isPickFace) {
                            isPickFace = true;
                            Date dateTwo = new Date();
                            reqTwo = dateTwo.getTime();
                            Bundle bundle = msg.getData();
                            String QRdate = bundle.getString("PROCESSOR_QRCODE_DATE");
                            numberAll = QRdate;
                            LogUtil.v("二维码返回  " + QRdate);

                            sendRequset("1", QRdate, "");
                            she.setLightState(she.light_green);
                            PlayAudioFile("二维码正常" + QRdate);
                        } else {
                            SelfToastUtil.getInstance().show("正在采集人脸，请勿做其他操作");
                        }


                        break;
                    case PROCESSOR_IDCODE:
                        // 接收到身份证 应该去网络判断
                        if (!isPickFace) {
                            isPickFace = true;
                            Date dateTwoID = new Date();
                            reqTwo = dateTwoID.getTime();
                            Bundle bundleID = msg.getData();
                            String IDdate = bundleID.getString("PROCESSOR_IDCODE");
                            LogUtil.v("身份证返回" + IDdate);
                            numberAll = IDdate;
                            sendRequset("2", IDdate, "");
                            she.setLightState(she.light_red);
                            PlayAudioFile("二维码正常" + IDdate);
                        } else {
                            SelfToastUtil.getInstance().show("正在采集人脸，请勿做其他操作");
                        }
                        break;
                    case PICK_FACE:
                        //如果接收到人脸， 对button 进行可操作
                        btAgain.setBackgroundResource(R.drawable.shape_confirm);
                        btConfig.setBackgroundResource(R.drawable.shape_orange);
                        btConfig.setClickable(true);
                        btAgain.setClickable(true);
                        break;
                    case CONTINUE_BRUSH:

                        break;
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        IDAndICFind();
        etScan.requestFocus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        etScan.requestFocus();
    }

    @Override
    protected int getView() {
        return R.layout.activity_anhui;
    }

    @Override
    public void init() {
        rlMessage = (RelativeLayout) findViewById(R.id.rl_show_message);
        svPreview = (SurfaceView) findViewById(R.id.sv_preview_track);
        m_titleFace = (ImageView) findViewById(R.id.iv_title_face);
        m_titleResult = (TextView) findViewById(R.id.tv_title_result);
        m_messageResult = (MyImageView) findViewById(R.id.iv_message_result);
        m_rlMessageFace = (RelativeLayout) findViewById(R.id.rl_face_pick);
        mllTitlebg = (LinearLayout) findViewById(R.id.ll_title_result);
        m_ivFace = (ImageView) findViewById(R.id.iv_face);
        btConfig = (Button) findViewById(R.id.bt_confirm);
        btAgain = (Button) findViewById(R.id.bt_again);
        btReset = (Button) findViewById(R.id.bt_reset);
        iv_Test = (ImageView) findViewById(R.id.iv_test);
        fmMask = (FaceMasks) findViewById(R.id.fm_mask_track);
        etScan = (EditText) findViewById(R.id.et_scan);

        svPreview.getWidth();
        svPreview.getHeight();
        changeFace(0);
        //初始化人脸资源
        facedetecter = new FaceDetecter();
        facedetecter.init(this, Global.FACEPP_KEY);
        facedetecter.setTrackingMode(true);

        //初始化摄像头
        activity = this;
        handleThread = new HandlerThread("dt");
        handleThread.start();
        detectHandler = new Handler(handleThread.getLooper());
        svPreview.getHolder().addCallback(this);
        svPreview.setKeepScreenOn(true);

        //点击事件
        btConfig.setOnClickListener(this);
        btAgain.setOnClickListener(this);
        btReset.setOnClickListener(this);

        //开启灯带控制
        initBote();
        //开启身份证读卡器
//        openIdRead();

//        //接口回调，10009 回调，
//        ResultManger.setNetResultListener(new NetResult() {
//            @Override
//            public void netResult(int type, final CheckResultBean s) {
//                //这里返回 说明 采集图片，那么久去切换页面 并进行人脸采集
//                if (type == 4) {
//                    //如果 返回的是 4 ，那说明返回10009  需要 录入 人脸照片
//                    changeFace(1);
//                } else {
//                    PickFace = false;
//                    isPickFace = false;
//                    changeFace(0);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (s != null) {
//                                SelfToastUtil.getInstance().show("该凭证未设置采集人脸");
//                                PlayAudioFile("该凭证未设置采集人脸");
////                                SelfToastUtil.getInstance().show(s.getMessage());
////                                PlayAudioFile(s.getMessage());
//                            } else {
//                                SelfToastUtil.getInstance().show("网络访问失败");
//                                PlayAudioFile("网络访问失败");
//                            }
//                        }
//                    });
//                }
//            }
//
//            @Override
//            public void faceAcceptResult(CheckResultBean s) {
//                // 当要去获取 人脸信息的时候，那么这里就有回调
//                PickFace = true;
//                basa64 = null;
//                checkResultBean = s;
//                final Message message = new Message();
//                message.what = PICK_FACE;
//                feceNeed = new Runnable() {
//                    @Override
//                    public void run() {
//                        if (PickFace) {
//                            if (null != basa64 && !basa64.equals("")) {
//                                PickFace = false;
////                                changeFace(1);
//                                mMyHandler.sendMessage(message);
//                            } else {
//                                LogUtil.v("需要录入人脸，但是没有找到人脸，所以我就要一直找");
//                                mMyHandler.postDelayed(this, 2000);
//                            }
//                        }
//                    }
//                };
//                mMyHandler.post(feceNeed);
//            }
//
//            @Override
//            public void faceSuccess(int type, String s) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        isSendFace = false;
//                        isPickFace = false;
//                        changeFace(0);
//                        basa64 = "";
//                        PickFace = false;
//                        mMyHandler.removeCallbacks(feceNeed);
//                        she.setLightState(she.light_green);
//                        SelfToastUtil.getInstance().show("人脸采集成功，谢谢使用");
//                        PlayAudioFile("人脸采集成功 谢谢使用");
//                    }
//                });
//            }
//
//            @Override
//            public void faceDefut(final String s) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        pickFaceNum++;
//
//                        isSendFace = false;
//                        changeFace(2);
//                        she.setLightState(she.light_red);
////                        SelfToastUtil.getInstance().show(s);
//                        if (pickFaceNum < 3) {
//                            PlayAudioFile("人脸采集失败 请从新采集");
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void oneFaceCheck(int type, String s) {
//
//            }
//        });

        FaceCj.SetFaceRectListener(new FacePickInterface() {
            @Override
            public void getFace(final RectF f) {
                fmMask.setFacePar(f);
            }

            @Override
            public void noFace() {
                fmMask.setFacePar(new RectF());
            }
        });

        FaceMasks.setOutFaceListener(new OutFace() {
            @Override
            public void faceOut() {
                //如果超出边框 那么就提示 并且不截图
                if (PickFace) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SelfToastUtil.getInstance().show("请将人脸至于绿框内");
                        }
                    });
                }
            }
        });

        //获取TTS引擎
        mSpeech = new TextToSpeech(AnhuiActivity.this, new AnhuiActivity.TTSListener());

        if (hasNavBar(AnhuiActivity.this)) {
            hideBottomUIMenu();
        }


    }

//    private void IDAndICFind() {
//        //身份证 和 Ic卡轮流 查询
//        runnableID = new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    try {
//                        String IDNumber = IDAndICHelper.ReadIDCardUsb();
//                        if (IDNumber != null && !IDNumber.equals("")) {
//                            // 那么就发送信息到 handler
//                            Message message = Message.obtain();
//                            message.what = PROCESSOR_IDCODE;
//                            Bundle bundle = new Bundle();
//                            bundle.putString("PROCESSOR_IDCODE", IDNumber);
//                            message.setData(bundle);
//                            mMyHandler.sendMessage(message);
//                        }
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//
//                }
//
//            }
//        };
//        ThreadManager.getThreadPool().execute(runnableID);
//
//    }

    private void initBote() {
        try {
            she = new SHExtends("/dev/ttyS3", "9600");
            she.open();
            she.setLightState(she.light_off);
        } catch (Exception e) {
            ToastUtil.showToast("灯带Com口异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_confirm:
                etScan.requestFocus();
                // 点击按钮，那么就 去提交数
                if (isSendFace) {
                    SelfToastUtil.getInstance().show("正在发送人脸数据数据，请稍后");
                    return;
                }
                if (null != basa64 && !basa64.equals("")) {
                    isSendFace = true;
                    FaceCheck.getInstance().FacePick(checkResultBean, basa64);
                } else {
                    SelfToastUtil.getInstance().show("图片抓取为空，请重新采集");
                }
                break;
            case R.id.bt_again:
                pickFaceNum = 0;
                etScan.requestFocus();
                isSendFace = false;
                she.setLightState(she.light_green);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btConfig.setClickable(false);
                        btAgain.setClickable(false);
                        changeFace(1);
                        btConfig.setBackgroundResource(R.drawable.shape_gray);
                        btAgain.setBackgroundResource(R.drawable.shape_gray);
                        m_ivFace.setImageResource(R.mipmap.facebgs);
                    }
                });

                // 重新开始 循环 所以 要  这个
                PickFace = true;
                basa64 = null;
                final Message message = new Message();
                message.what = PICK_FACE;
                feceNeed = new Runnable() {
                    @Override
                    public void run() {
                        if (PickFace) {
                            if (null != basa64 && !basa64.equals("")) {
                                PickFace = false;
                                mMyHandler.sendMessage(message);
                            } else {
                                LogUtil.v("需要录入人脸，但是没有找到人脸，所以我就要一直找");
                                mMyHandler.postDelayed(this, 2000);
                            }
                        }
                    }
                };
                mMyHandler.post(feceNeed);
                break;
            case R.id.bt_reset:
                pickFaceNum = 0;
                etScan.requestFocus();
                isSendFace = false;
                // 复位
                PickFace = false;
                isPickFace = false;
                changeFace(0);
                she.setLightState(she.light_off);
                break;
        }
    }

    public void Test(View view) {

        ToastUtil.showToast("我被点击了");
    }

    private void changeFace(final int i) {
        faceType = i;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //等待界面
                if (i == 0) {
                    PickFace = false;
                    isPickFace = false;
                    m_messageResult.setVisibility(View.VISIBLE);
                    m_rlMessageFace.setVisibility(View.GONE);
                    m_ivFace.setVisibility(View.GONE);
                    btConfig.setVisibility(View.GONE);
                    btAgain.setVisibility(View.GONE);
                    btAgain.setBackgroundResource(R.drawable.shape_gray);
                    btConfig.setBackgroundResource(R.drawable.shape_gray);
//                    m_titleResult.setTextSize(R.dimen.text_size_message_small_anhui_17);
                    m_titleResult.setTextColor(getResources().getColor(R.color.color_duck_blue_anhui));
                    m_titleResult.setText("请将身份证或二维码放置下方感应器");
                    m_titleFace.setImageResource(R.mipmap.happy);

                    mllTitlebg.setBackgroundResource(R.drawable.shape_face);

                }
                //采集人脸界面
                if (i == 1) {
                    m_messageResult.setVisibility(View.GONE);
                    m_rlMessageFace.setVisibility(View.VISIBLE);
                    m_ivFace.setVisibility(View.VISIBLE);
                    btConfig.setVisibility(View.VISIBLE);
                    btAgain.setVisibility(View.VISIBLE);
                    btConfig.setClickable(false);
                    btAgain.setClickable(false);
//                    m_titleResult.setTextSize(R.dimen.text_size_message_middle_anhui);
                    m_titleResult.setTextColor(getResources().getColor(R.color.color_duck_blue_anhui));
                    m_titleResult.setText("正在采集人脸信息...");
                    m_titleFace.setImageResource(R.mipmap.happy);

                    mllTitlebg.setBackgroundResource(R.drawable.shape_face);

                }

                //采集人脸界面 失败
                if (i == 2) {
                    m_messageResult.setVisibility(View.GONE);
                    m_rlMessageFace.setVisibility(View.VISIBLE);
                    m_ivFace.setVisibility(View.VISIBLE);
                    btConfig.setVisibility(View.VISIBLE);
                    btAgain.setVisibility(View.VISIBLE);

//                    m_titleResult.setTextSize(R.dimen.text_size_message_middle_anhui);
                    m_titleResult.setTextColor(getResources().getColor(R.color.color_orange_deep));
                    m_titleResult.setText("采集失败 请重试...");
                    m_titleFace.setImageResource(R.mipmap.fierce);
                    mllTitlebg.setBackgroundResource(R.drawable.shape_result_title);
                }
                // 人脸已经存在，就显示照片，
                if (i == 3) {
                    m_messageResult.setVisibility(View.GONE);
                    m_rlMessageFace.setVisibility(View.VISIBLE);
                    m_ivFace.setVisibility(View.VISIBLE);
                    btConfig.setVisibility(View.GONE);
                    btAgain.setVisibility(View.GONE);
                    //checkResultBean
                    try {
                        if (checkResultBean.getData().getBase64Pic() != null) {
                            m_ivFace.setImageBitmap(MyBitmapUtils.stringToBitmap((String) checkResultBean.getData().getBase64Pic()));
                        }
                    } catch (Exception e) {

                    }
//                    m_titleResult.setTextSize(R.dimen.text_size_message_middle_anhui);
                    m_titleResult.setTextColor(getResources().getColor(R.color.color_duck_blue_anhui));
                    m_titleResult.setText("证件已采集人脸，请进行对比...");
                    m_titleFace.setImageResource(R.mipmap.happy);
                    mllTitlebg.setBackgroundResource(R.drawable.shape_face);
                }
            }
        });


    }


    private static void sendRequset(String type, String qRdate, String rowKey) {
        if (qrCheck.equals(qRdate) && reqTwo - reqOne < betweenTime) {
            return;
        }
        if (null != qRdate) {
            qrCheck = qRdate;
            //首先 不为空， 第二，接口间隔为3秒，防止相同的卡重复检票
            QRcodeCheck.getInstance().checkTicketNeedFace(type, qRdate, rowKey);
            Date dateOne = new Date();
            reqOne = dateOne.getTime();
        }
    }

//    private void openIdRead() {
//        // USB 方式打开 身份证
//        IDopen = IDAndICHelper.startIdCardReader(activity);
//        if (IDopen) {
//            SelfToastUtil.getInstance().show("身份证模块已经打开");
////            SelfToastUtil.getInstance().show("");
////            ToastUtil.showToast("身份证模块已经打开");
//        } else {
//            SelfToastUtil.getInstance().show("身份证模块打开失败");
//        }
//
//    }

    @Override
    public void onPreviewFrame(final byte[] data, final Camera camera) {

        // 这个方法 让数据方向进行调整
        final byte[] datas = rotateYUV420Degree180(data, width, height);

        camera.setPreviewCallback(null);
        if (mCamera == null) return;
        detectHandler.post(new Runnable() {
            @Override
            public void run() {
                coseToBase64(datas, camera);
                try {
                    camera.setPreviewCallback(AnhuiActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        });
    }

    //这个方法处理图片 后期需要放在 子线程里面
    private void coseToBase64(byte[] data, Camera camera) {

        try {
            Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = true;
            YuvImage yuvimage = new YuvImage(
                    data,
                    ImageFormat.NV21,
                    previewSize.width,
                    previewSize.height,
                    null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);// 80--JPG图片的质量[0-100],100最高
            final byte[] rawImage = baos.toByteArray();
//        将rawImage转换成bitmap
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_4444;

            bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);

            if (bitmap != null) {
                bitmap1 = MyBitmapUtils.rotateBitmap(bitmap, 270, false);
            }

            //经过测试  bitmap1，不为空的情况下，bitmap_collect为空，是剪裁里面 检查不到人脸，返回为空
            if (bitmap1 != null) {
                bitmap_collect = FaceCj.cutFace(bitmap1, AnhuiActivity.this);

            }


            if (bitmap_collect != null) {
                basa64 = MyBitmapUtils.bitmapToBase64(bitmap_collect);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       SelfToastUtil.getInstance().show("人脸出现了");
//                        ToastUtil.showToast("人脸出现了");
                    }
                });
                if (PickFace) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            m_ivFace.setImageBitmap(bitmap_collect);
                        }
                    });
                }

                //  Environment.getExternalStorageDirectory().toString() + File.separator + Customer.FOLDER_NAME,
                MyBitmapUtils.saveBitmap(bitmap_collect, new File(Environment.getExternalStorageDirectory().toString() + File.separator + Customer.FOLDER_NAME + File.separator + "zyf.png"));
            }
        } catch (Exception e) {
            LogUtil.v("图片回收异常");
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera = Camera.open(0);
            mCamera.setDisplayOrientation(90);
            Camera.Parameters para = mCamera.getParameters();

            Point showingArea = new Point();
            WindowManager wm = (WindowManager) getSystemService(
                    Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            int screenWidth = display.getWidth();
            int screenHeight = display.getHeight();

            int topHeight = dip2px(activity, 25 + 44);//状态栏+titlebar
            showingArea.set(screenWidth, screenHeight - topHeight);

            width = 640;
            height = 480;
            // 预览变形的问题
            Log.e("size", "size w:" + width + "--h:" + height);

            para.setPreviewSize(width, height);
            mCamera.setParameters(para);
        } catch (Exception e) {
//            ToastUtil.showToast("无法找到摄像头，请确定摄像头已连接");
            SelfToastUtil.getInstance().show("无法找到摄像头，请确定摄像头已连接");
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mCamera == null) {
            return;
        }
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.setDisplayOrientation(90);
            mCamera.startPreview();
            mCamera.setPreviewCallback(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera == null) {
            return;
        }
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }


    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private byte[] rotateYUV420Degree180(byte[] data, int imageWidth, int imageHeight) {
        byte[] yuv = new byte[imageWidth * imageHeight * 3 / 2];
        int i = 0;
        int count = 0;
        for (i = imageWidth * imageHeight - 1; i >= 0; i--) {
            yuv[count] = data[i];
            count++;
        }
        i = imageWidth * imageHeight * 3 / 2 - 1;
        for (i = imageWidth * imageHeight * 3 / 2 - 1; i >= imageWidth
                * imageHeight; i -= 2) {
            yuv[count++] = data[i - 1];
            yuv[count++] = data[i];
        }
        return yuv;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            char pressedKey = (char) event.getUnicodeChar();
            barcode += pressedKey;
        }
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            if (barcode != null && !barcode.equals("")) {
                // 那么就去请求服务器
//                SelfToastUtil.getInstance(AnhuiActivity.this).show(etScan.getText().toString());
                Message message = Message.obtain();
                message.what = PROCESSOR_QRCODE;
                Bundle bundle = new Bundle();
                string = etScan.getText().toString();
                bundle.putString("PROCESSOR_QRCODE_DATE", string.trim());
                message.setData(bundle);
                mMyHandler.sendMessage(message);
                etScan.setText("");
                barcode = "";
            }
        }
        return super.dispatchKeyEvent(event);
    }


    //播放合成语音
    public static void PlayAudioFile(String str) {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        } else {
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_ADD, null);
    }

    /**
     * 检查是否存在虚拟按键栏
     *
     * @param context
     * @return
     */
    public static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     *
     * @return
     */
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
            }
        }
        return sNavBarOverride;
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
//                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


}
